package com.member.web.controller.shop;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.member.common.annotation.Log;
import com.member.common.core.controller.BaseController;
import com.member.common.core.domain.AjaxResult;
import com.member.common.core.page.TableDataInfo;
import com.member.common.enums.BusinessType;
import com.member.common.utils.DateUtils;
import com.member.common.utils.StringUtils;
import com.member.common.utils.bean.BeanValidators;
import com.member.common.utils.poi.ExcelUtil;
import com.member.common.utils.uuid.IdUtils;
import com.member.shop.domain.*;
import com.member.shop.dto.SysBizGoodsDto;
import com.member.shop.dto.SysBizGoodsTemplatebatchExportDto;
import com.member.shop.dto.SysBizGoodsTemplatebatchImportDto;
import com.member.shop.service.*;
import com.member.shop.vo.SpecsData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Validator;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 【商品】控制器
 *
 * @author lixinchen
 * @version 1.0
 * @date 2024-01-05
 **/
@RestController
@RequestMapping("/shop/goods")
public class SysBizGoodsController extends BaseController {
    @Resource
    private ISysBizGoodsService sysBizGoodsService;

    @Resource
    private ISysBizGoodsSkuService sysBizGoodsSkuService;

    @Resource
    private ISysBizShopSpecsService sysBizShopSpecsService;

    @Resource
    private ISysBizTenantService sysBizTenantService;

    /**
     * 查询商品列表
     */
    @PreAuthorize("@ss.hasPermi('shop:goods:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysBizGoods sysBizGoods) {
        startPage();
        setTenantId(sysBizGoods);
        List<SysBizGoodsDto> list = sysBizGoodsService.selectSysBizGoodsList(sysBizGoods);
        return getDataTable(list);
    }

    private void setTenantId(SysBizGoods sysBizGoods) {
        Long tenantId = getTenantId();
        if (tenantId != null && tenantId > 0) {
            sysBizGoods.setTenantId(tenantId);
        }
    }

    /**
     * 导出商品列表
     */
    @PreAuthorize("@ss.hasPermi('shop:goods:export')")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysBizGoods sysBizGoods) {
        setTenantId(sysBizGoods);
        List<SysBizGoodsDto> list = sysBizGoodsService.selectSysBizGoodsList(sysBizGoods);
        ExcelUtil<SysBizGoodsDto> util = new ExcelUtil<SysBizGoodsDto>(SysBizGoodsDto.class);
        util.exportExcel(response, list, "商品数据");
    }

    /**
     * 获取商品管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('shop:goods:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        //根据id查询[详细信息]
        SysBizGoods data = sysBizGoodsService.selectSysBizGoodsById(id);
        List<SpecsData> specsDataList = data.getSpecsDataList();
        if (specsDataList.size() > 0) {
            for (SpecsData specsData : specsDataList) {
                SysBizShopSpecs sysBizGoodsSpecsData = new SysBizShopSpecs();

                sysBizGoodsSpecsData.setParentId(specsData.getSpecsId());
                List<SysBizShopSpecs> goodsSpecsDataList = sysBizShopSpecsService.selectSysBizShopSpecsList(sysBizGoodsSpecsData);
                List<SpecsData> childs = specsData.getChilds();

                List<SpecsData> newChilds = new ArrayList<>();

                List<String> selects = new ArrayList<>();
                for (SysBizShopSpecs bizGoodsSpecsData : goodsSpecsDataList) {
                    SpecsData e = new SpecsData();
                    e.setSpecsId(bizGoodsSpecsData.getId());
                    e.setSpecsName(bizGoodsSpecsData.getSpecsName());
                    for (SpecsData child : childs) {
                        if (child.getSpecsId().equals(e.getSpecsId())) {
                            selects.add(e.getSpecsName());
                        }
                    }
                    newChilds.add(e);
                }
                specsData.setSelects(selects);
                specsData.setChilds(newChilds);
            }
        }

        LambdaQueryWrapper<SysBizGoodsSku> queryWrapper = new LambdaQueryWrapper<SysBizGoodsSku>();
        queryWrapper.eq(data.getId() != null, SysBizGoodsSku::getGoodsId, data.getId());
        List<SysBizGoodsSku> sysBizGoodsSkus = sysBizGoodsSkuService.selectSysBizGoodsSkuList(queryWrapper);
        HashMap<String, Object> result = new HashMap<>();
        result.put("goods", data);
        result.put("skuList", sysBizGoodsSkus);
        result.put("specs", specsDataList);
        result.put("details", data.getDetails());
        return AjaxResult.success(result);
    }

    /**
     * 修改商品(上架和推荐)
     */
    @PreAuthorize("@ss.hasPermi('shop:goods:editOne')")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PostMapping("/editOne")
    public AjaxResult editOne(@RequestBody SysBizGoods sysBizGoods) {
        return toAjax(sysBizGoodsService.updateSysBizGoods(sysBizGoods));
    }


    /**
     * 修改商品排序
     */
    @PreAuthorize("@ss.hasPermi('shop:goods:editOne')")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PostMapping("/updateSort")
    public AjaxResult updateSort(@RequestBody SysBizGoods sysBizGoods) {
        return toAjax(sysBizGoodsService.update(new LambdaUpdateWrapper<SysBizGoods>()
                .eq(SysBizGoods::getId, sysBizGoods.getId())
                .set(SysBizGoods::getOrderNum, sysBizGoods.getOrderNum())));

    }

    /**
     * 修改商品管理
     */
    @PreAuthorize("@ss.hasPermi('shop:goods:edit')")
    @Log(title = "商品管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GoodDetails goodDetails) {
        SysBizGoods goods = goodDetails.getGoods();
        List<SysBizGoodsSku> skuList = goodDetails.getSkuList();
        setGoodsPrice(goods, skuList);
        goods.setCategoryId(goodDetails.getGoods().getCategoryId());
        List<SpecsData> specs = goodDetails.getSpecs();
        List<SpecsData> selectSpecs = getSelectSpecs(specs);
        goods.setSpecsData(JSON.toJSONString(selectSpecs));
        String username = this.getUsername();
        goods.setDetails(goodDetails.getDetails());
        goods.setUpdateBy(username);

        Date nowDate = DateUtils.getNowDate();
        if (goods.getOrderNum() == null) {
            goods.setOrderNum(1L);
        }
        String firstUnit = skuList.stream().map(SysBizGoodsSku::getUnit).findFirst().orElse(null);
        goods.setUnit(firstUnit);
        int count = sysBizGoodsService.updateSysBizGoods(goods);
        extracted(goods, skuList, specs, username, nowDate);
        return toAjax(count);
    }

    @Resource
    private ISysBizCarouselService sysBizCarouselService;
    @Resource
    private ISysBizJingangService sysBizJingangService;
    @Resource
    private ISysBizAgreementService sysBizAgreementService;

    /**
     * 删除商品
     */
    @PreAuthorize("@ss.hasPermi('shop:goods:remove')")
    @Log(title = "商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        //判断该商品是否被轮播图
        if (sysBizCarouselService.hasExist(id)) {
            return warn("该商品已被轮播图所选中，请修改后删除");
        }
        //判断该商品是否被金刚区
        if (sysBizJingangService.hasExist(id)) {
            return warn("该商品已被金刚区所选中，请修改后删除");
        }
        //判断该商品是否被设置会员招商商品
        if (sysBizAgreementService.hasExist(id)) {
            return warn("该商品会员招商商品所选中，请修改后删除");
        }
        return toAjax(sysBizGoodsService.deleteSysBizGoodsById(id));
    }

    /**
     * 新增商品管理
     */
    @PreAuthorize("@ss.hasPermi('shop:goods:add')")
    @Log(title = "新增商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GoodDetails goodDetails) {
        SysBizGoods goods = goodDetails.getGoods();
        setTenantId(goodDetails.getGoods());
        List<SysBizGoodsSku> skuList = goodDetails.getSkuList();
        setGoodsPrice(goods, skuList);
        List<SpecsData> specs = goodDetails.getSpecs();

        List<SpecsData> selectSpecs = getSelectSpecs(specs);
        goods.setDetails(goodDetails.getDetails());
        goods.setSpecsData(JSON.toJSONString(selectSpecs));
        String username = this.getUsername();
        goods.setCreateBy(username);
        goods.setUpdateBy(username);
        if (goods.getOrderNum() == null) {
            goods.setOrderNum(1L);
        }
        Date nowDate = DateUtils.getNowDate();
        goods.setUpdateTime(nowDate);
        goods.setCreateTime(nowDate);

        String firstUnit = skuList.stream()
                .map(SysBizGoodsSku::getUnit)
                .findFirst()
                .orElse(null);

        goods.setUnit(firstUnit);
        int i = sysBizGoodsService.insertSysBizGoods(goods);
        // 新增商品标签
        extracted(goods, skuList, specs, username, nowDate);
        return toAjax(1);
    }

    private void setGoodsPrice(SysBizGoods goods, List<SysBizGoodsSku> skuList) {
//        // 最小市场价格
//        BigDecimal minMarketPrice = BigDecimal.ZERO;
//        // 最大市场价格
//        BigDecimal maxMarketPrice = BigDecimal.ZERO;
//
//        // 最小销售价格
//        BigDecimal minSalesPrice = BigDecimal.ZERO;
//        // 最大销售价格
//        BigDecimal maxSalesPrice = BigDecimal.ZERO;

        if (!CollectionUtils.isEmpty(skuList)) {
            Optional<BigDecimal> minVip1Price = skuList.stream()
                    .filter(sku -> sku.getStatus() == 0)
                    .map(sku -> {
                        BigDecimal vip1Price = sku.getVip1Price();
                        BigDecimal longUnitNumber = new BigDecimal(sku.getLongUnitNumber());
                        return vip1Price.divide(longUnitNumber, 2, BigDecimal.ROUND_HALF_UP);
                    })
                    .filter(Objects::nonNull)
                    .min(BigDecimal::compareTo);

            Optional<BigDecimal> maxVip1Price = skuList.stream()
                    .filter(sku -> sku.getStatus() == 0)
                    .map(sku -> {
                        BigDecimal vip1Price = sku.getVip1Price();
                        BigDecimal longUnitNumber = new BigDecimal(sku.getLongUnitNumber());
                        return vip1Price.divide(longUnitNumber, 2, BigDecimal.ROUND_HALF_UP);
                    })
                    .filter(Objects::nonNull)
                    .max(BigDecimal::compareTo);

            Optional<BigDecimal> minMarketPrice = skuList.stream()
                    .filter(sku -> sku.getStatus() == 0)
                    .map(sku -> {
                        BigDecimal memberMarketPrice = sku.getMemberMarketPrice();
                        BigDecimal longUnitNumber = new BigDecimal(sku.getLongUnitNumber());
                        return memberMarketPrice.divide(longUnitNumber, 2, BigDecimal.ROUND_HALF_UP);
                    })
                    .filter(Objects::nonNull)
                    .min(BigDecimal::compareTo);

            Optional<BigDecimal> maxMarketPrice = skuList.stream()
                    .filter(sku -> sku.getStatus() == 0)
                    .map(sku -> {
                        BigDecimal memberMarketPrice = sku.getMemberMarketPrice();
                        BigDecimal longUnitNumber = new BigDecimal(sku.getLongUnitNumber());
                        return memberMarketPrice.divide(longUnitNumber, 2, BigDecimal.ROUND_HALF_UP);
                    })
                    .filter(Objects::nonNull)
                    .max(BigDecimal::compareTo);

            // 设置商品的价格属性
            minVip1Price.ifPresent(goods::setMinSalesPrice);
            maxVip1Price.ifPresent(goods::setMaxSalesPrice);
            minMarketPrice.ifPresent(goods::setMinMarketPrice);
            maxMarketPrice.ifPresent(goods::setMaxMarketPrice);
        }
    }

    private List<SpecsData> getSelectSpecs(List<SpecsData> specs) {
        List<SpecsData> selectSpecs = new ArrayList<>();
        for (SpecsData spec : specs) {
            SpecsData specsData = new SpecsData();
            List<SpecsData> newChilds = new ArrayList<>();
            List<SpecsData> childs = spec.getChilds();
            List<String> selects = spec.getSelects();
            for (SpecsData child : childs) {
                if (selects.contains(child.getSpecsName())) {
                    newChilds.add(child);
                }
            }
            specsData.setSelects(selects);
            specsData.setChilds(newChilds);
            specsData.setSpecsId(spec.getSpecsId());
            specsData.setSpecsName(spec.getSpecsName());
            selectSpecs.add(specsData);

        }
        return selectSpecs;
    }

    private void extracted(SysBizGoods goods, List<SysBizGoodsSku> skuList, List<SpecsData> specs, String username, Date nowDate) {
        //清除原来的
        sysBizGoodsSkuService.deleteSysBizGoodsSkuByGoodsId(goods.getId());
        for (SysBizGoodsSku sysBizGoodsSku : skuList) {
            if(StringUtils.isEmpty(sysBizGoodsSku.getSpecsKey())){
                sysBizGoodsSku.setSkuCode(IdUtils.fastSimpleUUID());
            }
            sysBizGoodsSku.setGoodsId(goods.getId());
            sysBizGoodsSku.setTenantId(goods.getTenantId());
            sysBizGoodsSku.setUpdateBy(username);
            sysBizGoodsSku.setUpdateTime(nowDate);
            List<SpecsData> specsDataList = new ArrayList<>();
            String[] split = sysBizGoodsSku.getSpecsKey().split(",");
            for (String s : split) {
                for (SpecsData spec : specs) {
                    List<SpecsData> childs = spec.getChilds();
                    for (SpecsData child : childs) {
                        if (s.equals(child.getSpecsName())) {
                            SpecsData specsData = new SpecsData();
                            specsData.setSpecsId(spec.getSpecsId());
                            specsData.setSpecsName(spec.getSpecsName());
                            specsData.setStatus(sysBizGoodsSku.getStatus());
                            ArrayList<SpecsData> childList = new ArrayList<>();
                            childList.add(child);
                            specsData.setChilds(childList);
                            specsDataList.add(specsData);
                        }
                    }
                }
            }
            String skuSpecsData = JSON.toJSONString(specsDataList);
//            sysBizGoodsSku.setPic(goods.getCover());
            sysBizGoodsSku.setCreateBy(username);
            sysBizGoodsSku.setCreateTime(nowDate);
            sysBizGoodsSku.setSpecsData(skuSpecsData);
            sysBizGoodsSkuService.insertSysBizGoodsSku(sysBizGoodsSku);
        }
    }


    /**
     * 查询商品列表
     */
    @PreAuthorize("@ss.hasPermi('shop:goods:list')")
    @GetMapping("/listSku")
    public TableDataInfo listSku(SysBizGoods sysBizGoods) {
        startPage();
        setTenantId(sysBizGoods);
        List<SysBizGoodsSku> sysBizGoodsSkuList = sysBizGoodsSkuService.selectSkuList(sysBizGoods);
        return getDataTable(sysBizGoodsSkuList);
    }

    @Autowired
    protected Validator validator;
    @Resource
    private ISysBizShopCategoryService sysBizShopCategoryService;

    /**
     * 新增商品模板
     */
    @PreAuthorize("@ss.hasPermi('shop:goods:list')")
    @Log(title = "商品模板", businessType = BusinessType.INSERT)
    @PostMapping("/batchImport")
    public AjaxResult batchImport(MultipartFile file, HttpServletResponse response) throws Exception {
        ExcelUtil<SysBizGoodsTemplatebatchImportDto> util = new ExcelUtil<>(SysBizGoodsTemplatebatchImportDto.class);
        List<SysBizGoodsTemplatebatchImportDto> batchImporList = util.importExcel(file.getInputStream());

        //记录失败的list
        List<SysBizGoodsTemplatebatchExportDto> sysBizGoodsTemplatebatchExportDtos = new ArrayList<SysBizGoodsTemplatebatchExportDto>();

        if (CollectionUtils.isEmpty(batchImporList)) {
            return AjaxResult.error("列表不能为空");
        }
        int successNum = 0;
        int failureNum = 0;
        int failureNumCount = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysBizGoodsTemplatebatchImportDto sysBizGoodsTemplateImpor : batchImporList) {
            ++failureNumCount;
            SysBizGoods sysBizGoods;
            try {
                BeanValidators.validateWithException(validator, sysBizGoodsTemplateImpor);

                List<SysBizTenant> sysBizTenants = sysBizTenantService.selectSysBizTenantList(new LambdaQueryWrapper<SysBizTenant>()
                        .eq(SysBizTenant::getName, sysBizGoodsTemplateImpor.getTenantName()));


                if (CollectionUtils.isEmpty(sysBizTenants)) {
//                    ++failureNum;
//                    SysBizGoodsTemplatebatchExportDto sysBizGoodsTemplatebatchExportDto = new SysBizGoodsTemplatebatchExportDto();
//                    BeanUtils.copyProperties(sysBizGoodsTemplateImpor, sysBizGoodsTemplatebatchExportDto);
//                    sysBizGoodsTemplatebatchExportDto.setFailureReason("没找到对应的站点名称");
//                    sysBizGoodsTemplatebatchExportDtos.add(sysBizGoodsTemplatebatchExportDto);
                    throw new RuntimeException("没找到对应的站点名称");
                }
                SysBizTenant sysBizTenant = sysBizTenants.get(0);
                //一级名称
                String firstCategoryName = sysBizGoodsTemplateImpor.getFirstCategoryName();

                List<SysBizShopCategory> sysBizShopCategories = sysBizShopCategoryService.selectSysBizShopCategoryList(new LambdaQueryWrapper<SysBizShopCategory>()
                        .eq(SysBizShopCategory::getCategoryName, firstCategoryName)
                        .eq(SysBizShopCategory::getTenantId, sysBizTenant.getId())
                        .eq(SysBizShopCategory::getParentId, 0)
                        .eq(SysBizShopCategory::getDeleted, 0));
                SysBizShopCategory sysBizShopCategory;
                if (CollectionUtils.isEmpty(sysBizShopCategories)) {
                    sysBizShopCategory = new SysBizShopCategory();
                    sysBizShopCategory.setCategoryName(firstCategoryName);
                    sysBizShopCategory.setTenantId(sysBizTenant.getId());
                    sysBizShopCategory.setParentId(0L);
                    sysBizShopCategory.setOrderNum(1L);
                    sysBizShopCategory.setDisplayed(0L);
                    sysBizShopCategoryService.insertSysBizShopCategory(sysBizShopCategory);
                } else {
                    sysBizShopCategory = sysBizShopCategories.get(0);
                }

                //二级名称
                String secondCategoryName = sysBizGoodsTemplateImpor.getSecondCategoryName();

                List<SysBizShopCategory> sysBizShopCategories2 = sysBizShopCategoryService.selectSysBizShopCategoryList(new LambdaQueryWrapper<SysBizShopCategory>()
                        .eq(SysBizShopCategory::getCategoryName, secondCategoryName)
                        .eq(SysBizShopCategory::getTenantId, sysBizTenant.getId())
                        .eq(SysBizShopCategory::getParentId, sysBizShopCategory.getId())
                        .eq(SysBizShopCategory::getDeleted, 0));
                SysBizShopCategory sysBizShopCategory2;
                if (CollectionUtils.isEmpty(sysBizShopCategories2)) {
                    sysBizShopCategory2 = new SysBizShopCategory();
                    sysBizShopCategory2.setCategoryName(secondCategoryName);
                    sysBizShopCategory2.setTenantId(sysBizTenant.getId());
                    sysBizShopCategory2.setParentId(sysBizShopCategory.getId());
                    sysBizShopCategory2.setOrderNum(1L);
                    sysBizShopCategory2.setDisplayed(0L);
                    sysBizShopCategoryService.insertSysBizShopCategory(sysBizShopCategory2);
                } else {
                    sysBizShopCategory2 = sysBizShopCategories2.get(0);
                }


                List<SysBizGoods> sysBizGoods1 = sysBizGoodsService.selectSysBizGoodsList(new LambdaQueryWrapper<SysBizGoods>()
                        .eq(SysBizGoods::getTenantId, sysBizTenant.getId())
                        .eq(SysBizGoods::getName, sysBizGoodsTemplateImpor.getGoodsName())
                        .eq(SysBizGoods::getCategoryId, sysBizShopCategory.getId())
                        .eq(SysBizGoods::getCategoryTwoId, sysBizShopCategory2.getId())
                        .eq(SysBizGoods::getDeleted, 0));

                if (CollectionUtils.isEmpty(sysBizGoods1)) {
                    sysBizGoods = new SysBizGoods();
                    sysBizGoods.setTenantId(sysBizTenant.getId());
                    sysBizGoods.setCategoryId(sysBizShopCategory.getId());
                    sysBizGoods.setCategoryTwoId(sysBizShopCategory2.getId());
                    sysBizGoods.setName(sysBizGoodsTemplateImpor.getGoodsName());
                    sysBizGoods.setGrounding(0L);
                    sysBizGoods.setOrderNum(sysBizGoodsTemplateImpor.getOrderNum());
                    sysBizGoods.setActualSales(sysBizGoodsTemplateImpor.getActualSales());
                    sysBizGoods.setRealitySales(0L);
                    sysBizGoods.setGoodsDescribe(sysBizGoodsTemplateImpor.getGoodsDescribe());
                    sysBizGoods.setDelivery(sysBizGoodsTemplateImpor.getDelivery());
                    sysBizGoods.setService(sysBizGoodsTemplateImpor.getService());
                    sysBizGoods.setCreateBy(getUsername());
                    sysBizGoods.setUpdateBy(getUsername());
                    //保存商品
                    sysBizGoodsService.insertSysBizGoods(sysBizGoods);
                } else {
                    sysBizGoods = sysBizGoods1.get(0);
                }


                //判断sku是否存在
                List<SysBizGoodsSku> sysBizGoodsSkuExist = sysBizGoodsSkuService.selectSysBizGoodsSkuList(new LambdaQueryWrapper<SysBizGoodsSku>()
                        .eq(SysBizGoodsSku::getGoodsId, sysBizGoods.getId())
                        .eq(SysBizGoodsSku::getErpProductCode, sysBizGoodsTemplateImpor.getErpProductCode())
                        .eq(SysBizGoodsSku::getSpecsKey, sysBizGoodsTemplateImpor.getSpecsKeyName())
                );
                if (!CollectionUtils.isEmpty(sysBizGoodsSkuExist)) {
//                    ++failureNum;
//                    SysBizGoodsTemplatebatchExportDto sysBizGoodsTemplatebatchExportDto = new SysBizGoodsTemplatebatchExportDto();
//                    BeanUtils.copyProperties(sysBizGoodsTemplateImpor, sysBizGoodsTemplatebatchExportDto);
//                    sysBizGoodsTemplatebatchExportDto.setFailureReason("该商品的sku已存在");
//                    sysBizGoodsTemplatebatchExportDtos.add(sysBizGoodsTemplatebatchExportDto);
                    throw new RuntimeException("该商品的SKU已存在");
                }


                SysBizGoodsSku sysBizGoodsSku = new SysBizGoodsSku();
                sysBizGoodsSku.setGoodsId(sysBizGoods.getId());
                sysBizGoodsSku.setErpProductCode(sysBizGoodsTemplateImpor.getErpProductCode());

                //父规格
                String specsName = sysBizGoodsTemplateImpor.getSpecsName();
                //查询有没有 没有就创建有就获取id
                List<SysBizShopSpecs> sysBizShopSpecs = sysBizShopSpecsService.selectSysBizShopSpecsList(new LambdaQueryWrapper<SysBizShopSpecs>()
                        .eq(SysBizShopSpecs::getSpecsName, specsName)
                        .eq(SysBizShopSpecs::getTenantId, sysBizTenant.getId())
                        .eq(SysBizShopSpecs::getParentId, 0)
                        .eq(SysBizShopSpecs::getDeleted, 0));
                SysBizShopSpecs sysBizShopSpec;
                if (CollectionUtils.isEmpty(sysBizShopSpecs)) {
                    sysBizShopSpec = new SysBizShopSpecs();
                    sysBizShopSpec.setSpecsName(specsName);
                    sysBizShopSpec.setTenantId(sysBizTenant.getId());
                    sysBizShopSpec.setParentId(0L);
                    sysBizShopSpec.setOrderNum(1L);
                    sysBizShopSpecsService.insertSysBizShopSpecs(sysBizShopSpec);
                } else {
                    sysBizShopSpec = sysBizShopSpecs.get(0);
                }

                //子规格
                String specsKeyName = sysBizGoodsTemplateImpor.getSpecsKeyName();
                //查询有没有 没有就创建有就获取id
                List<SysBizShopSpecs> sysBizShopSpecs2 = sysBizShopSpecsService.selectSysBizShopSpecsList(new LambdaQueryWrapper<SysBizShopSpecs>()
                        .eq(SysBizShopSpecs::getSpecsName, specsKeyName)
                        .eq(SysBizShopSpecs::getTenantId, sysBizTenant.getId())
                        .eq(SysBizShopSpecs::getParentId, sysBizShopSpec.getId())
                        .eq(SysBizShopSpecs::getDeleted, 0));
                SysBizShopSpecs sysBizShopSpec2;
                if (CollectionUtils.isEmpty(sysBizShopSpecs2)) {
                    sysBizShopSpec2 = new SysBizShopSpecs();
                    sysBizShopSpec2.setSpecsName(specsKeyName);
                    sysBizShopSpec2.setTenantId(sysBizTenant.getId());
                    sysBizShopSpec2.setParentId(sysBizShopSpec.getId());
                    sysBizShopSpec2.setOrderNum(1L);
                    sysBizShopSpecsService.insertSysBizShopSpecs(sysBizShopSpec2);
                } else {
                    sysBizShopSpec2 = sysBizShopSpecs2.get(0);
                }

                sysBizGoodsSku.setSpecsKey(sysBizGoodsTemplateImpor.getSpecsKeyName());

                ArrayList<SpecsData> childs = new ArrayList<SpecsData>();
                SpecsData childSpecsData = new SpecsData();
                childSpecsData.setSpecsId(sysBizShopSpec.getId());
                childSpecsData.setSpecsName(sysBizShopSpec.getSpecsName());
                childSpecsData.setStatus(0);
                ArrayList<SpecsData> childs2 = new ArrayList<SpecsData>();
                SpecsData childSpecsData2 = new SpecsData();
                childSpecsData2.setSpecsId(sysBizShopSpec2.getId());
                childSpecsData2.setSpecsName(sysBizShopSpec2.getSpecsName());
                childs2.add(childSpecsData2);
                childSpecsData.setChilds(childs2);
                childs.add(childSpecsData);

                sysBizGoodsSku.setSpecsData(JSON.toJSONString(childs));
                sysBizGoodsSku.setTenantId(sysBizTenant.getId());
                sysBizGoodsSku.setLongUnit(sysBizGoodsTemplateImpor.getLongUnit());
                sysBizGoodsSku.setLongUnitNumber(sysBizGoodsTemplateImpor.getLongUnitNumber());
                sysBizGoodsSku.setUnit(sysBizGoodsTemplateImpor.getUnit());
                sysBizGoodsSku.setMemberSalesPrice(sysBizGoodsTemplateImpor.getVip1Price());
                sysBizGoodsSku.setMemberMarketPrice(sysBizGoodsTemplateImpor.getVip1Price());
                sysBizGoodsSku.setStock(1000L);
                sysBizGoodsSku.setLimitNumber(1000);
                sysBizGoodsSku.setFrozenStockCount(0L);
                sysBizGoodsSku.setStatus(0);
                sysBizGoodsSku.setVip1Price(sysBizGoodsTemplateImpor.getVip1Price());
                sysBizGoodsSku.setVip2Price(sysBizGoodsTemplateImpor.getVip1Price());
                sysBizGoodsSku.setVip3Price(sysBizGoodsTemplateImpor.getVip1Price());
                sysBizGoodsSku.setVip4Price(sysBizGoodsTemplateImpor.getVip1Price());
                sysBizGoodsSku.setVip5Price(sysBizGoodsTemplateImpor.getVip1Price());
                sysBizGoodsSku.setActivityPrice(sysBizGoodsTemplateImpor.getVip1Price());
                sysBizGoodsSku.setSkuCode(IdUtils.fastSimpleUUID());
                sysBizGoodsSkuService.insertSysBizGoodsSku(sysBizGoodsSku);


                List<SysBizGoodsSku> sysBizGoodsSkus = sysBizGoodsSkuService.selectSysBizGoodsSkuList(new LambdaQueryWrapper<SysBizGoodsSku>()
                        .eq(SysBizGoodsSku::getGoodsId, sysBizGoods.getId()));


                List<String> specsData = sysBizGoodsSkus.stream()
                        .map(SysBizGoodsSku::getSpecsData)
                        .filter(Objects::nonNull) // 过滤掉 null 值
                        .collect(Collectors.toList());

                JSONArray combinedChilds = new JSONArray();
                List<String> selects = new ArrayList<>();
                JSONObject combinedObject = null;

                for (String data : specsData) {
                    JSONArray dataArray = JSONArray.parseArray(data);
                    JSONObject item = dataArray.getJSONObject(0);

                    // 获取并合并子规格
                    JSONArray childs3 = item.getJSONArray("childs");
                    for (Object child : childs3) {
                        combinedChilds.add(child);
                        selects.add(((JSONObject) child).getString("specsName"));
                    }

                    // 初始化combinedObject，这里假设所有输入对象具有相同的specsId和specsName
                    if (combinedObject == null) {
                        combinedObject = new JSONObject();
                        combinedObject.put("specsId", item.getIntValue("specsId"));
                        combinedObject.put("specsName", item.getString("specsName"));
                    }
                }

                // 添加合并后的childs和selects
                combinedObject.put("childs", combinedChilds);
                combinedObject.put("selects", selects);

                // 将结果放入JSONArray中
                JSONArray resultArray = new JSONArray();
                resultArray.add(combinedObject);
                sysBizGoods.setSpecsData(resultArray.toJSONString());
                setGoodsPrice(sysBizGoods, sysBizGoodsSkus);
                sysBizGoodsService.updateSysBizGoods(sysBizGoods);


            } catch (Exception e) {
                ++failureNum;
                String msg = "<br/>第" + failureNumCount + "条：导入失败:"+e.getMessage();
                failureMsg.append(msg);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "导入失败！共 " + failureNum + " 条数据格式不正确:");
            return AjaxResult.success(failureMsg.toString());
        } else {
            successMsg.insert(0, "数据已全部导入成功！");
            return AjaxResult.success(successMsg.toString());
        }
    }
}

